const {
  clearCountDown,   // 清空倒计时
  getIndexBoxInfo,    // 获取用户当前正在倒计时的宝箱信息
  openBox,    // 打开宝箱，将奖品暂存
  obtainPrize,    // 领取奖品，multiple为倍数
} = require('../lib/action')

module.exports = function (app) { return new Handler(app); };
let Handler = function (app) { this.app = app; };
let handler = Handler.prototype;

// 打开宝箱页面
handler.openBoxPage = async function (msg, session, next){
  let { uid, frontendId } = session;
  try{
    // 获取已拥有宝箱数量和待收取宝箱数量，当前倒计时的宝箱ID和宝箱创建时间
    let {ownBoxLen, waitOpenBoxLen, nowCountDownBox} = await getIndexBoxInfo.call(this, uid, frontendId);
    next(null, {code: 200, ownBoxLen, waitOpenBoxLen, nowCountDownBox});
  }catch(err){
    next(err, {code: 500, msg: err.message});
  }
}

// 看视频清空倒计时
handler.clearCountDown = async function (msg, session, next) {
  let { id } = msg;
  let { uid, frontendId } = session;
  try{
    //清空倒计时
    await clearCountDown.call(this, uid, frontendId, id);
    next(null, {code: 200 });
  }catch(err){
    next(err, {code: 500, msg: err.message});
  }
}

// 打开宝箱
handler.openBox = async function (msg, session, next) {
  let { uid, frontendId } = session;
  try{
    // 打开宝箱，将奖品暂存
    let res = await openBox.call(this, session, uid, frontendId);
    next(null, {code: 200, ...res});
  }catch(err){
    next(err, {code: 500, msg: err.message});
  }
}

// 普通领取
handler.obtainPrize = async function (msg, session, next) {
  try{
    // 普通领取
    await obtainPrize.call(this, session);
    next(null, {code: 200});
  }catch(err){
    next(err, {code: 500, msg: err.message});
  }
}

// 双倍打开宝箱
handler.doubleObtainPrize = async function (msg, session, next) {
  try{
    // 双倍打开宝箱
    await obtainPrize.call(this, session, 2);
    next(null, {code: 200});
  }catch(err){
    next(err, {code: 500, msg: err.message});
  }
}
